package com.tc.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

/**
 * JWT工具类
 */
public class JWT {
    private static final String SECRET = "ybbx"; // 密钥，建议使用更复杂的字符串
    private static final long EXPIRATION = 1000 * 60 * 60 * 24; // 24小时
    private static final long REFRESH_EXPIRATION = 1000 * 60 * 60 * 24 * 7; // 7天

    /**
     * 创建访问令牌
     */
    public static String createToken(String subject, String id, Map<String, Object> claims) {
        JwtBuilder builder = Jwts.builder();
        return builder.setSubject(subject)
                .setIssuedAt(new Date())
                .setId(id)
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
    }

    /**
     * 创建刷新令牌
     */
    public static String createRefreshToken(String subject, String id) {
        JwtBuilder builder = Jwts.builder();
        return builder.setSubject(subject)
                .setIssuedAt(new Date())
                .setId(id)
                .setExpiration(new Date(System.currentTimeMillis() + REFRESH_EXPIRATION))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
    }

    /**
     * 解析令牌
     */
    public static Claims parseToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 验证令牌是否有效
     */
    public static boolean validateToken(String token) {
        try {
            Claims claims = parseToken(token);
            return claims != null && !claims.getExpiration().before(new Date());
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从令牌中获取用户名
     */
    public static String getUsernameFromToken(String token) {
        Claims claims = parseToken(token);
        return claims != null ? claims.getSubject() : null;
    }

    /**
     * 从令牌中获取用户ID
     */
    public static String getUserIdFromToken(String token) {
        Claims claims = parseToken(token);
        return claims != null ? claims.getId() : null;
    }

    /**
     * 获取令牌过期时间
     */
    public static Date getExpirationFromToken(String token) {
        Claims claims = parseToken(token);
        return claims != null ? claims.getExpiration() : null;
    }

    /**
     * 获取访问令牌过期时间(秒)
     */
    public static long getExpirationTime() {
        return EXPIRATION / 1000;
    }

    /**
     * 获取刷新令牌过期时间(秒)
     */
    public static long getRefreshExpirationTime() {
        return REFRESH_EXPIRATION / 1000;
    }
}
